package com.yxt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import yxt.util.ImageHelper;
@Controller
@RequestMapping("file")
public class FileUpload {
	@SuppressWarnings("finally")
	@RequestMapping(value="/uploadFilePhisics.do",method=RequestMethod.POST)
	public @ResponseBody String uploadFile(HttpServletRequest request,HttpServletResponse response ) throws Exception {
			boolean success = false;
			//文件的完全物理路径
			String fileRealPath = "";	
			//传过来的要保存到的位置（相对路径）
			String filePath = request.getParameter("filePath");
			//文件类型
			String type = request.getParameter("type");
			//文件名称
			String fileName = "";
			String prefix = request.getServletContext().getRealPath("/");
			try {
			   	MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
				MultipartFile file = req.getFile("file");
				fileName = file.getOriginalFilename();
				//物理路径前缀
				
				//绝对目录
				String dirRealPath = prefix + filePath;
				//目录不存在就新建目录
				File dir = new File(dirRealPath);
				if(!dir.exists()) { 
					dir.mkdirs();
				}
				//文件的完全物理路径
				fileRealPath = dirRealPath + fileName;
				File f = new File(fileRealPath);
				if(f.exists()) { //如果存在，修改文件名,加（1）、(2)...后缀
					int dot = fileName.lastIndexOf('.'); 
					String pureFileName = fileName.substring(0, dot); //不带后缀的纯文件名
					String suffix = fileName.substring(dot);
					//判断有几个重名的文件
	                int i = 1;
	                do {
	                	fileName = pureFileName + "(" + i + ")" + suffix;
	                	String tempFileRealPath = dirRealPath + fileName;
	                	File temp = new File(tempFileRealPath);
	                	if(!temp.exists()) {
	                		break;
	                	}
	                	i++;
	                }while(true);
		            //更新文件实际路径
		            fileRealPath = dirRealPath + fileName;
				}
			    //上传文件
				InputStream stream = file.getInputStream();
				FileOutputStream fs = new FileOutputStream(fileRealPath);
		        byte[] buffer =new byte[1024*1024];
		        int byteread = 0; 
		        while ((byteread=stream.read(buffer))!=-1)
		        {
		           fs.write(buffer,0,byteread);
		           fs.flush();
		        } 
		        fs.close();
		        stream.close();
		        success = true;
			}catch(Exception e) {
				success = false;
			} finally {
				String relativePath = filePath + fileName;
				String small_url = filePath + "small_" + fileName;
				if("pic".equals(type)) {
					new ImageHelper().compressPic(prefix+filePath, prefix+filePath, fileName, "small_"+fileName, 100, 100, true); 
				}
				relativePath = relativePath.replace("\\", "/");
				small_url = small_url.replace("\\", "/");
				return "{success: " + success +",url: \"" + relativePath + "\", small_url: \"" + small_url + "\"}";
			}
	}
	@RequestMapping(value="/download.do",method=RequestMethod.GET)
	public @ResponseBody void downloadFile(HttpServletRequest request,HttpServletResponse response ) throws Exception {
		String filename = request.getParameter("filename");
		   /******
		   * 设置文件不在浏览器中直接打开，而且通过filename参数可以设置建议保存文件名，这个文件名会出现在save as文件框
		   * 文件名中，作为默认保存名。如果不设置的话，则会把Servlet的名称作为默认的保存名
		   */
		   response.setHeader("Content-disposition","attachment; filename="+filename);
		   String filePath = request.getServletContext().getRealPath("/")+"files\\"+filename;
		   filePath = filename = new String(filePath.getBytes("ISO8859_1"), "UTF-8");
		   System.out.println(filePath);
		   FileInputStream fs = new FileInputStream(new File(filePath));
		   try{
			   int b = 0;
			   PrintWriter out = response.getWriter();
			   while((b=fs.read())!=-1) {
			   out.write(b);
			   }
			   fs.close();
			   out.close();
		   }catch(Exception e){
		    e.printStackTrace();
		   }
	}
}
